﻿/******************************************************************************
	Cobalt - utility libraries for building XNA games
	Copyright (C) 2008 Philip Djonov

	This program is free software; you can redistribute it and/or modify it
	under the terms of the GNU General Public License as published by the Free
	Software Foundation; either version 2 of the License, or (at your option)
	any later version.

	This program is distributed in the hope that it will be useful, but
	WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
	or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
	for more details.

	You should have received a copy of the GNU General Public License along
	with this program; if not, write to the
	
		Free Software Foundation, Inc.
		51 Franklin Street, Fifth Floor
		Boston, MA  02110-1301, USA.
******************************************************************************/

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Graphics.PackedVector;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;

namespace Cobalt.Content.Pipeline.Quake.Bsp
{
	[ContentImporter( ".bsp", DisplayName = "BSP Importer", DefaultProcessor = "BspProcessor" )]
	public partial class BspContentImporter : ContentImporter<ImportedBspContent>
	{
		public override ImportedBspContent Import( string filename, ContentImporterContext context )
		{
			BspImporter importer = new BspImporter();

			string q3root, mapPath;
			GetQuake3Paths( filename, out q3root, out mapPath );

			importer.Fs = new QuakeFs();
			importer.Fs.SearchPaths.Add( q3root );

			string baseq3 = Path.Combine( Path.GetDirectoryName( q3root ), "baseq3" );
			if( Directory.Exists( baseq3 ) )
				importer.Fs.SearchPaths.Add( baseq3 );

			importer.Fs.OpeningPath += delegate( object sender, DependencyEventArgs e )
			{
				context.AddDependency( e.DependencyPath );
			};

			importer.Logger = context.Logger;

			return importer.Import( mapPath );
		}

		private void GetQuake3Paths( string bspPath, out string q3root, out string mapPath )
		{
			string bspDir = Path.GetDirectoryName( bspPath );
			string bspDirName = Path.GetFileName( bspDir );

			if( string.Compare( bspDirName, "maps", StringComparison.InvariantCultureIgnoreCase ) != 0 )
				throw new DirectoryNotFoundException( "Unable to find the Quake 3 root directory." );

			q3root = Path.GetDirectoryName( bspDir );
			mapPath = "maps/" + Path.GetFileName( bspPath );
		}
	}
}